{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Video Segmentation with SAM 3\n",
    "\n",
    "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_segmentation.ipynb)\n",
    "\n",
    "This notebook demonstrates how to use SAM 3 for video segmentation and tracking. SAM 3 provides:\n",
    "\n",
    "- **Text prompts**: Segment objects using natural language (e.g., \"person\", \"car\")\n",
    "- **Point prompts**: Add clicks to segment and refine objects\n",
    "- **Object tracking**: Track segmented objects across all video frames\n",
    "- **Time series support**: Process GeoTIFF time series with georeferencing\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Installation\n",
    "\n",
    "SAM 3 requires CUDA-capable GPU. Install with:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# %pip install \"segment-geospatial[samgeo3]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Import Libraries\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from samgeo import SamGeo3Video, download_file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initialize Video Predictor\n",
    "\n",
    "The `SamGeo3Video` class provides a simplified API for video segmentation. It automatically uses all available GPUs.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam = SamGeo3Video()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load a Video\n",
    "\n",
    "You can load from different sources:\n",
    "- MP4 video file\n",
    "- Directory of JPEG frames\n",
    "- Directory of GeoTIFFs (for remote sensing time series)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = \"https://github.com/opengeos/datasets/releases/download/videos/cars.mp4\"\n",
    "video_path = download_file(url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.set_video(video_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.show_video(video_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Text-Prompted Segmentation\n",
    "\n",
    "Use natural language to describe objects. SAM 3 finds all instances and tracks them.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Segment all car in the video\n",
    "sam.generate_masks(\"car\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualize Results\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Show the first frame with masks\n",
    "sam.show_frame(0, axis=\"on\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://github.com/user-attachments/assets/563dcda7-24e2-43f5-95b1-5706f72a3cc0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Show multiple frames in a grid\n",
    "sam.show_frames(frame_stride=20, ncols=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://github.com/user-attachments/assets/cc08c90b-3227-4bcd-acfa-2cb3e6c89bc5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Remove Objects\n",
    "\n",
    "Remove specific objects by ID and re-propagate.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Remove object 2 and re-propagate\n",
    "sam.remove_object(2)\n",
    "sam.propagate()\n",
    "sam.show_frame(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://github.com/user-attachments/assets/d4d98bf1-4580-466d-a7dc-19485fbeb466)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Point Prompts\n",
    "\n",
    "Add objects back or refine segmentation using point prompts.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Add back object 2 with a positive point click\n",
    "sam.add_point_prompts(\n",
    "    points=[[335, 203]],  # [x, y] coordinates\n",
    "    labels=[1],  # 1=positive, 0=negative\n",
    "    obj_id=2,\n",
    "    frame_idx=0,\n",
    ")\n",
    "sam.propagate()\n",
    "sam.show_frame(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://github.com/user-attachments/assets/dc1f1b64-654a-4c57-a892-2679e02ffe29)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Refine with Multiple Points\n",
    "\n",
    "Use positive and negative points to refine the mask.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Refine to segment only the shirt (not pants)\n",
    "sam.add_point_prompts(\n",
    "    points=[[335, 195], [335, 220]],  # detect windshield, not the car\n",
    "    labels=[1, 0],  # positive, negative\n",
    "    obj_id=2,\n",
    "    frame_idx=0,\n",
    ")\n",
    "sam.propagate()\n",
    "sam.show_frames(frame_stride=20, ncols=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://github.com/user-attachments/assets/48b454d8-ba9c-43df-b001-fba6f86792b1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Save Results\n",
    "\n",
    "Save masks as images or create an output video.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.makedirs(\"output\", exist_ok=True)\n",
    "\n",
    "# Save mask images\n",
    "sam.save_masks(\"output/masks\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save video with blended masks\n",
    "sam.save_video(\"output/segmented.mp4\", fps=25)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Close Session\n",
    "\n",
    "Close the session to free GPU resources.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To completely shutdown and free all resources:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.shutdown()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "geo",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
